<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace common\user\model;

use think\Db;
use think\Model;
use think\Config;
use common\user\model\ThirdPartyUserModel;

class UserModel extends Model
{
    protected $type = [
        'more' => 'array',
    ];

    public function doMobile($user)
    {
        $result = $this->where('mobile', $user['mobile'])->where(['user_type' => 2])->find();


        if (!empty($result)) {
            $comparePasswordResult = cmf_compare_password($user['user_pass'], $result['user_pass']);
            $hookParam             = [
                'user'                    => $user,
                'compare_password_result' => $comparePasswordResult
            ];
            hook_one("user_login_start", $hookParam);
            if ($comparePasswordResult) {
                //拉黑判断。
                if ($result['user_status'] == 0) {
                    return 3;
                }
                // var_dump($result->data['id']);exit;
                session('user', $result->toArray());
                session('ADMIN_ID',$result->data['id']);
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip'   => get_client_ip(0, true),
                ];
                $this->where('id', $result["id"])->update($data);
                $token = cmf_generate_user_token($result["id"], 'web');
                if (!empty($token)) {
                    session('token', $token);
                }
                return 0;
            }
            return 1;
        }
        $hookParam = [
            'user'                    => $user,
            'compare_password_result' => false
        ];
        hook_one("user_login_start", $hookParam);
        return 2;
    }

    public function doName($user)
    {
        $result = $this->where('user_login', $user['user_login'])->where(['user_type' => 2])->find();
        if (!empty($result)) {
            $comparePasswordResult = cmf_compare_password($user['user_pass'], $result['user_pass']);
            $hookParam             = [
                'user'                    => $user,
                'compare_password_result' => $comparePasswordResult
            ];
            hook_one("user_login_start", $hookParam);
            if ($comparePasswordResult) {
                //拉黑判断。
                if ($result['user_status'] == 0) {
                    return 3;
                }
                session('user', $result->toArray());
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip'   => get_client_ip(0, true),
                ];
                $result->where('id', $result["id"])->update($data);
                $token = cmf_generate_user_token($result["id"], 'web');
                if (!empty($token)) {
                    session('token', $token);
                }
                return 0;
            }
            return 1;
        }
        $hookParam = [
            'user'                    => $user,
            'compare_password_result' => false
        ];
        hook_one("user_login_start", $hookParam);
        return 2;
    }

    public function doEmail($user)
    {

        $result = $this->where('user_email', $user['user_email'])->where(['user_type' => 2])->find();

        if (!empty($result)) {
            $comparePasswordResult = cmf_compare_password($user['user_pass'], $result['user_pass']);
            $hookParam             = [
                'user'                    => $user,
                'compare_password_result' => $comparePasswordResult
            ];
            hook_one("user_login_start", $hookParam);
            if ($comparePasswordResult) {

                //拉黑判断。
                if ($result['user_status'] == 0) {
                    return 3;
                }
                session('user', $result->toArray());
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip'   => get_client_ip(0, true),
                ];
                $this->where('id', $result["id"])->update($data);
                $token = cmf_generate_user_token($result["id"], 'web');
                if (!empty($token)) {
                    session('token', $token);
                }
                return 0;
            }
            return 1;
        }
        $hookParam = [
            'user'                    => $user,
            'compare_password_result' => false
        ];
        hook_one("user_login_start", $hookParam);
        return 2;
    }


    public function doThird($user)
    {
        // 先查询第三方帐号信息,然后再查用户表信息
        $ThirdPartyUser = new ThirdPartyUserModel;
        $where = [];
        $where['app_id'] = $user['app_id'];
        $where['openid'] = $user['openid'];
        $where['type'] = $user['type'];
        if (isset($user['unionid']) && !empty($user['unionid'])) {
            $where['union_id'] = $user['unionid'];
        }
        $third_user_info = $ThirdPartyUser::get($where);
        if (empty($third_user_info)) {
           return false;
        }else{
            $Third_result = $this->where('id', $third_user_info['user_id'])->where(['user_type' => 2])->find();
        }
        if (!empty($Third_result)) {
            // 判断是否有父级id
            if(!empty($Third_result['parent_id'])){
                $parent_result = $this->where('id', $Third_result['id'])->where(['user_type' => 2])->find();
                if(empty($parent_result['parent_id'])){
                    $parent_result =$Third_result;
                }
            }else{
                // 强制父id为自己
                $parent_result =$Third_result;
            }

            $hookParam             = [
                'user'                    => $user,
                'compare_password_result' => true
            ];
            hook_one("user_login_start", $hookParam);

                //拉黑判断。
                if ($parent_result['user_status'] == 0) {
                    return 3;
                }
                session('user', $parent_result->toArray());
                session('user.third', $Third_result->toArray());
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip'   => get_client_ip(0, true),
                ];
                $this->where('id', $parent_result["id"])->where('id', $Third_result["id"])->update($data);
                $ThirdPartyUser->where('id', $third_user_info["id"])->update($data);
                $token = cmf_generate_user_token($Third_result["id"], $user['deviceType']);
                if (!empty($token)) {
                    session('token', $token);
                }
            return 1;
        }
        $hookParam = [
            'user'                    => $user,
            'compare_password_result' => false
        ];
        hook_one("user_login_start", $hookParam);
        return 2;
    }

    public function register($user,$type,$device_type='web')
    {
        switch ($type){
            case 1:
                $result = Db::name("user")->where('user_login', $user['user_login'])->find();
                break;
            case 2:
                $result = Db::name("user")->where('mobile', $user['mobile'])->find();
                break;
             case 3:
                 $result = Db::name("user")->where('user_email', $user['user_email'])->find();
                 break;
            default:
                $result = 0;
        }

        $userStatus = 1;

        if (cmf_is_open_registration()) {
            $userStatus = 2;
        }
        if (empty($result)) {
            $data   = [
                'user_login'      => empty($user['user_login']) ? '' : $user['user_login'],
                 'user_email'      => empty($user['user_email']) ? '' : $user['user_email'],
                'mobile'          => empty($user['mobile']) ? '' : $user['mobile'],
                 'user_nickname'   =>empty($user['user_nickname']) ? '' : $user['user_nickname'],
		 'view_uuid'       => md5(md5(md5($user['user_login']))),
		// 'user_pass'       => cmf_password($user['user_pass']),
                'user_pass'       => empty($user['user_pass']) ? cmf_password($user['password']) : cmf_password($user['user_pass']), 
                'parent_id'      => empty($user['parent_id']) ? 0 : $user['parent_id'],
                 'sex'      => empty($user['sex']) ? 0 : $user['sex'],
                 'avatar'      => empty($user['avatar']) ? 0 : $user['avatar'],
                'last_login_ip'   => get_client_ip(0, true),
                'create_time'     => time(),
                'last_login_time' => time(),
                'user_status'     => $userStatus,
                "user_type"       => 2,//默认是普通会员
            ];
            $userId = Db::name("user")->insertGetId($data);
            $data   = Db::name("user")->where('id', $userId)->find();
            $role_id = Config::get('user_role');
            Db::name('RoleUser')->insert(["role_id" => $role_id, "user_id" => $userId]);
            cmf_update_current_user($data);
            $token = cmf_generate_user_token($userId, $device_type);            //生成用户token
            if (!empty($token)) {
                session('token', $token);
            }
            if (!$userId) {
                return 2;
            }
            return 0;
        }
        return $result;
    }

    /**
     * 通过邮箱重置密码
     * @param $email
     * @param $password
     * @return int
     */
    public function emailPasswordReset($email, $password)
    {
        $result = $this->where('user_email', $email)->find();
        if (!empty($result)) {
            $data = [
                'user_pass' => cmf_password($password),
            ];
            $this->where('user_email', $email)->update($data);
            return 0;
        }
        return 1;
    }

    /**
     * 通过手机重置密码
     * @param $mobile
     * @param $password
     * @return int
     */
    public function mobilePasswordReset($mobile, $password)
    {
        $userQuery = Db::name("user");
        $result    = $userQuery->where('mobile', $mobile)->find();
        if (!empty($result)) {
            $data = [
                'user_pass' => cmf_password($password),
            ];
            $userQuery->where('mobile', $mobile)->update($data);
            return 0;
        }
        return 1;
    }

    public function editData($user)
    {
        $userId = cmf_get_current_user_id();

        if (isset($user['birthday'])) {
            $user['birthday'] = strtotime($user['birthday']);
        }


            $field ='user_nickname,sex,birthday,user_url,signature,more';

        if ($this->allowField($field)->save($user, ['id' => $userId])) {
            $userInfo = $this->where('id', $userId)->find();
            cmf_update_current_user($userInfo->toArray());
            return 1;
        }
        return 0;
    }

    /**
     * 用户密码修改
     * @param $user
     * @return int
     */
    public function editPassword($user)
    {
        $userId    = cmf_get_current_user_id();
        $userQuery = Db::name("user");
        if ($user['password'] != $user['repassword']) {
            return 1;
        }
        $pass = $userQuery->where('id', $userId)->find();
        if (!cmf_compare_password($user['old_password'], $pass['user_pass'])) {
            return 2;
        }
        $data['user_pass'] = cmf_password($user['password']);
        $userQuery->where('id', $userId)->update($data);
        return 0;
    }

    public function comments()
    {
        $userId               = cmf_get_current_user_id();
        $userQuery            = Db::name("Comment");
        $where['user_id']     = $userId;
        $where['delete_time'] = 0;
        $favorites            = $userQuery->where($where)->order('id desc')->paginate(10);
        $data['page']         = $favorites->render();
        $data['lists']        = $favorites->items();
        return $data;
    }

    public function deleteComment($id)
    {
        $userId              = cmf_get_current_user_id();
        $userQuery           = Db::name("Comment");
        $where['id']         = $id;
        $where['user_id']    = $userId;
        $data['delete_time'] = time();
        $userQuery->where($where)->update($data);
        return $data;
    }
    /**
     * 绑定用户手机号
     */
    public function bindingMobile($user)
    {
        $userId          = cmf_get_current_user_id();
        $data ['mobile'] = $user['username'];
        Db::name("user")->where('id', $userId)->update($data);
        $userInfo = Db::name("user")->where('id', $userId)->find();
        cmf_update_current_user($userInfo);
        return 0;
    }

    /**
     * 绑定用户邮箱
     */
    public function bindingEmail($user)
    {
        $userId              = cmf_get_current_user_id();
        $data ['user_email'] = $user['username'];
        Db::name("user")->where('id', $userId)->update($data);
        $userInfo = Db::name("user")->where('id', $userId)->find();
        cmf_update_current_user($userInfo);
        return 0;
    }
    /**
     * 绑定用户手机号
     */
    public function bandingMobile($user)
    {
        $userId          = cmf_get_current_user_id();
        $data ['mobile'] = $user['new_mobile'];
        $result = Db::name("user")->where('id', $userId)->update($data);
        if (!$result) {
            return 1;
        }
        $userInfo = Db::name("user")->where('id', $userId)->find();
        cmf_update_current_user($userInfo);
        return 0;
    }

    /**
     * 用户邮箱
     */
    public function bandingEmail($user)
    {
        $userId              = cmf_get_current_user_id();
        $data ['user_email'] = $user['user_email'];
        $result = Db::name("user")->where('id', $userId)->update($data);
        if (!$result) {
            return 1;
        }
        $userInfo = Db::name("user")->where('id', $userId)->find();
        cmf_update_current_user($userInfo);
        return 0;
    }

    /**
     * 用户扩展资料数据修改
     */
    public function updateMore($more)
    {
        $userId   = cmf_get_current_user_id();
        $result =  Db::name("user")->where('id', $userId)->update(['more'=>$more]);
        if (!$result) {
            return 1;
        }
        $userInfo = Db::name("user")->where('id', $userId)->find();
        cmf_update_current_user($userInfo);
        return 0;
    }

    /**
     * 修改主页大图
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function editHome($data)
    {
        $userId   = cmf_get_current_user_id();
        $result = Db::name('user')->where('id', $userId)->update($data);
        if (!$result) {
            return 1;
        }
        $userInfo = Db::name('user')->where('id',$userId)->find();
        cmf_update_current_user($userInfo);
        return 0;
    }

    /**
     * 修改用户头像
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function editAvatar($data)
    {
        $userId   = cmf_get_current_user_id();
        $result = Db::name("user")->where('id', $userId)->update($data);
        if (!$result) {
            return 1;
        }
        $userInfo = Db::name('user')->where('id',$userId)->find();
        cmf_update_current_user($userInfo);
        return 0;
    }
    
}
